import asyncio
import websockets


async def echo(websocket):
    try:
        # 在这里可以添加任何你想检查的条件
        while True:
            message = await websocket.recv()
            print(f"Received: {message}")
            if "quit" in message:
                # 如果收到的消息包含 "quit"，则断开连接
                break
            await websocket.send(message)
    except websockets.ConnectionClosedOK:
        print("Connection closed by client")
    finally:
        # 关闭WebSocket连接
        await websocket.close(reason="Client requested to quit")


async def main():
    async with websockets.serve(echo, "localhost", 8970):
        await asyncio.Future()  # 永远运行


if __name__ == "__main__":
    asyncio.run(main())
